package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.Emp;
import com.itheima.pojo.EmpExpr;
import com.itheima.service.EmpExprService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmpServiceImpl extends ServiceImpl<EmpMapper, Emp> implements EmpService {
    @Autowired
    private EmpExprService empExprService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveEmp(Emp emp) {
        //保存员工数据
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        emp.setPassword("123456");

        this.save(emp);
        //保存员工工作经历

        if (emp.getExprList() != null && !emp.getExprList().isEmpty()) {
            //设置关联关系
            emp.getExprList().forEach(expr -> expr.setEmpId(emp.getId()));
            empExprService.saveBatch(emp.getExprList());
        }

    }

    @Override
    public Emp getEmpById(Integer id) {
        //根据id查询员工数据
        Emp emp = this.getById(id);
        LambdaQueryWrapper<EmpExpr> qw = new LambdaQueryWrapper<>();
        qw.eq(EmpExpr::getEmpId, emp.getId());
        //根据员工id查询员工工作经历数据
        List<EmpExpr> list = empExprService.list(qw);
        emp.setExprList(list);
        return emp;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateEmp(Emp emp) {
        //修改员工数据
        emp.setUpdateTime(LocalDateTime.now());
        this.updateById(emp);

        //删除员工工作经历数据
        empExprService.remove(new LambdaQueryWrapper<EmpExpr>().eq(EmpExpr::getEmpId, emp.getId()));

        //保存员工工作经历数据
        if (emp.getExprList() != null && !emp.getExprList().isEmpty()) {
            emp.getExprList().forEach(expr -> expr.setEmpId(emp.getId()));
            empExprService.saveBatch(emp.getExprList());
        }

    }

    @Override
    public void deleteEmpByIds(List<Integer> ids) {
        //删除员工数据
        this.removeByIds(ids);

        //删除员工工作经历数据
        //select * from emp_expr where emp_id in (ids)
        empExprService.remove(new LambdaUpdateWrapper<EmpExpr>().in(EmpExpr::getEmpId,ids));

    }
}
